<?php

namespace app\api\controller\app;

use app\admin\model\Org;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shoporder;
use app\admin\model\Shopstaff;
use app\admin\model\Userbalance;
use app\admin\model\Usercoin;
use app\admin\model\Usercoupon;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['autoLogin','auth','getCode'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function getCode(){

        $mobile = $this->request->param('mobile');

        $userModel = new \app\admin\model\User();
        $checkUser = $userModel->where('mobile',$mobile)->find();
        if(!$checkUser){
            $this->error("用户不存在");
        }

        $sms_template = Config::get("database.sms_template");
        $sms_sign = Config::get("database.sms_sign");

        $template = $sms_template;
        $code = mt_rand(1000, 9999);
        $sign = $sms_sign;

        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->sign($sign)
            ->param(['code' => $code])
            ->send();
        if ($ret) {
            $this->redis->set($mobile, $code, 60 * 30);
            $this->success('发送成功');
        } else {
            $this->error("发送失败！失败原因：" . $alisms->getError());

        }
    }


    public function updatePhone()
    {

        $phoneData = $this->request->param('phoneData');
        $phoneIv = $this->request->param('phoneIv');
        $code = $this->request->param('code');
        $user = $this->auth->getUser();

        $orgId = $this->request->param('orgId');
        $orgModel = new Org();
        $org = $orgModel->where('id',$orgId)->find();
        if(!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);


        $ret = $this->app->auth->session($code);
        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $session_key = $ret['session_key'];
            $decryptedPhoneData = $this->app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
            $phoneNumber = $decryptedPhoneData['phoneNumber'];
            $userModel = new \app\admin\model\User();
            $phoneNumber = $decryptedPhoneData['phoneNumber'];
            if ($user['mobile'] == $phoneNumber) {
                $this->success("", $phoneNumber);
            } else {
                $findUser = $userModel->where('org_id',$orgId)->where('mobile', $phoneNumber)->find();
                if ($findUser) {
                    $this->error("此手机号已绑定了其它账号,请更换其他手机号");
                }
                $userModel->where('id', $user['id'])->update(['mobile' => $phoneNumber]);
                $this->success('成功', $phoneNumber);
            }


        }

    }

    public function auth()
    {



        $config = [
            'app_id' => "wx763ae61820ee8dc5",
            'secret' => "7f3cb7af2cc125ee68ac9bade62d4b03",
            'response_type' => 'array',
            'log' => [
            ],
        ];

        error_log("=====auth======".json_encode($config));
        $app = Factory::miniProgram($config);

        $code = $this->request->param('code');

        $phoneData = $this->request->param('phoneData');
        $phoneIv = $this->request->param('phoneIv');
        $ret = $app->auth->session($code);


        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $openid = $ret['openid'];
            $session_key = $ret['session_key'];
            $userWeixinModel = new Userweixin();
            $userwx = $userWeixinModel->where('openid', $openid)->find();
            if ($userwx) {
                $ret = $this->auth->direct($userwx['user_id']);
                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id', $userwx['user_id'])->find();
                $phoneNumber = $user['mobile'];

                $ret = $this->auth->direct($user['id']);
                $token = $this->auth->getToken();
                $data = array();
                $data['session_key'] = $session_key;
                $data['token'] = $token;


                if($user['mobile'] == ""){
                    if($phoneIv != "") {
                        $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                        $phoneNumber = $decryptedPhoneData['phoneNumber'];
                        $userModel->where('id',$user['id'])->update(['mobile'=>$phoneNumber]);
                    }
                }


                $avatar = $user['avatar'];
                if($avatar != ''){
                    $avatar = cdnurl($avatar,true);
                }
                $data['avatar'] = $avatar;
                $data['mobile'] = $phoneNumber;
                $data['username'] = "微信用户";
                $this->success('登录成功', $data);

            } else {
                $userModel = new \app\admin\model\User();
                if($phoneIv != ""){
                    $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                    $phoneNumber = $decryptedPhoneData['phoneNumber'];
                    $isFindUser = $userModel->where('mobile', $phoneNumber)->find();
                    if ($isFindUser) {
                        $id = $isFindUser['id'];
                    }else{
                        $db = array();
                        $db['group_id'] = 1;
                        $db['username'] = "微信用户";
                        $db['mobile'] = $phoneNumber;
                        $db['createtime'] = time();
                        $db['status'] = 'normal';
                        $id = $userModel->insertGetId($db);
                    }
                }else{
                    $phoneNumber = "";

                    $db = array();
                    $db['group_id'] = 1;
                    $db['username'] = "微信用户";
                    $db['mobile'] = "";
                    $db['createtime'] = time();
                    $db['status'] = 'normal';
                    $id = $userModel->insertGetId($db);
                }

                $userWeixinModel->insert(['user_id'=>$id,'openid'=>$openid]);
                $ret = $this->auth->direct($id);
                $token = $this->auth->getToken();

                $data = array();
                $avatarUrl = "";
                $data['session_key'] = $session_key;
                $data['token'] = $token;
                $data['avatar'] = $avatarUrl;
                $data['username'] = "微信用户";
                $data['mobile'] = $phoneNumber;


                $this->success('登录成功', $data);

            }


        }
    }


    public function updateUserInfo()
    {

        $user = $this->auth->getUser();
        $avatar = $this->request->param('avatar');
        $db = array();
        if ($avatar != '') {
            $db['avatar'] = $avatar;
        }
        $userModel = new \app\admin\model\User();
        $userModel->where('id', $user['id'])->update($db);

        $this->success('成功');
    }



    public function getInfo()
    {

        $user =$this->auth->getUser();
        $deviceId = $this->request->param('deviceId');
        $deviceModel= new \app\admin\model\Device();
        $shop_id = -1;
        $device = $deviceModel->where('device_id',$deviceId)->find();
        if($device){
            $shop_id = $device['agent_id'];
        }
        $userCoinModel = new Usercoin();
        $ret = array();
        $ret['user'] = $user['username'];
        $ret['mobile'] = $user['mobile'];
        $ret['coin'] = $userCoinModel->userCoin($user['id'],$shop_id);
        $ret['avatar'] = cdnurl($user['avatar'],true);
        $this->success('',$ret);
    }


}
